package com.ggbz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ggbz.entity.CounselorClasses;
import com.ggbz.entity.Users;
import com.ggbz.mapper.CounselorClassesMapper;
import com.ggbz.service.CounselorClassesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ggbz.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * <p>
 * 辅导员负责班级表，存储辅导员与班级的关联关系 服务实现类
 * </p>
 *
 * @author ggbz
 * @since 2025-03-08
 */
@Service
public class CounselorClassesServiceImpl extends ServiceImpl<CounselorClassesMapper, CounselorClasses> implements CounselorClassesService {
    private final CounselorClassesMapper counselorClassesMapper;
    private final UsersService usersService;

    @Autowired
    public CounselorClassesServiceImpl(CounselorClassesMapper counselorClassMapper,
                                     UsersService userService) {
        this.counselorClassesMapper = counselorClassMapper;
        this.usersService = userService;
    }

    @Override
    public List<CounselorClasses> getCounselorClasses(Long counselorId) {
        // 验证用户身份
        Users counselor = usersService.getById(counselorId);
        if (counselor == null || !"counselor".equals(counselor.getRole())) {
            throw new RuntimeException("用户不是辅导员或不存在");
        }
        return counselorClassesMapper.selectClassesByCounselorId(counselorId);
    }

    @Override
    @Transactional
    public void addCounselorClass(CounselorClasses counselorClass) {
        // 1. 验证辅导员身份
        //counselorId和userId相同
        Users counselor = usersService.getById(counselorClass.getCounselorId());
        if (counselor == null || !"counselor".equals(counselor.getRole())) {
            throw new RuntimeException("用户不是辅导员或不存在");
        }

        // 2. 检查是否已存在相同记录
        QueryWrapper<CounselorClasses> wrapper = new QueryWrapper<>();
        wrapper.eq("counselor_id", counselorClass.getCounselorId())
                .eq("class_name", counselorClass.getClassName());
        if (counselorClassesMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("该班级已分配给此辅导员");
        }

        // 3. 执行插入
        if (counselorClassesMapper.insert(counselorClass) == 0) {
            throw new RuntimeException("添加失败");
        }
    }


    @Override
    @Transactional
    public void updateCounselorClass(Long counselorId, String oldClassName, String newClassName) {
        // 1. 验证原记录是否存在
        QueryWrapper<CounselorClasses> oldWrapper = new QueryWrapper<>();
        oldWrapper.eq("counselor_id", counselorId)
                .eq("class_name", oldClassName);
        if (counselorClassesMapper.selectCount(oldWrapper) == 0) {
            throw new RuntimeException("原负责关系不存在");
        }

        // 2. 检查新班级名称是否已存在（同一个辅导员下）
        QueryWrapper<CounselorClasses> newWrapper = new QueryWrapper<>();
        newWrapper.eq("counselor_id", counselorId)
                .eq("class_name", newClassName);
        if (counselorClassesMapper.selectCount(newWrapper) > 0) {
            throw new RuntimeException("新班级名称已存在");
        }

        // 3. 执行更新（先删除旧记录，再插入新记录）
        counselorClassesMapper.delete(oldWrapper);

        CounselorClasses newRecord = new CounselorClasses();
        newRecord.setCounselorId(Math.toIntExact(counselorId));
        newRecord.setClassName(newClassName);
        if (counselorClassesMapper.insert(newRecord) == 0) {
            throw new RuntimeException("更新失败");
        }
    }

    /**
     * 删除辅导员负责的班级
     *
     * @param counselorId 辅导员ID
     * @param className   班级名称
     * @return 删除是否成功
     */
    @Transactional
    @Override
    public boolean deleteCounselorClass(Long counselorId, String className) {
        try {
            // 调用DAO层方法删除记录
            getBaseMapper().deleteByCounselorIdAndClassName(counselorId, className);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}
